import os
from src.base_class import BaseClass
from src.config import config
import requests
from src.exts import myredis
from src.global_var import Gkey, Keys
class WxUtil(BaseClass):
    def __init__(self,logger=None):
        super().__init__(logger)
        self.base_url = "https://api.weixin.qq.com"
    def genUrl(self, path):
        return f"{self.base_url}{path}"
    def set_accesstoken(self,accesstoken):
        self.logger.info(f"set_accesstoken:{accesstoken}")
        key =Gkey(Keys.WX_ACCESSTOKEN)
        myredis.setex(key, 7200, accesstoken)
    def set_test_token(self,prd_token):
        if os.environ.get("FLASK_ENV")!="production":
            return
        url = f"http://119.91.232.205:7878/wx/set_accesstoken?token={prd_token}"

        payload={}
        headers = {
            'token': '',
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
            'Authorization': 'Bearer '
        }
        response = requests.request("GET", url, headers=headers, data=payload)
        print(response.text)
    def get_once_token(self):
        url=self.genUrl(f"/cgi-bin/token?grant_type=client_credential&appid={config.wx_appid}&secret={config.wx_secret}")
        response = requests.get(url)
        result = response.json()
        return result
    
    def get_qrcode(self,trial='1'):
        url = self.genUrl(f"/wxa/getwxacodeunlimit?access_token={self.get_accesstoken()}")
        playload = {
            "scene": "scene",
            "page": "pages/index/index",
            "check_path": False,
            "is_hyaline": True,
            "width": 200
        }
        if trial=='1':
            playload['env_version'] = 'trial'
        result= requests.post(url,json=playload,timeout=10)
        return result.content
    def get_accesstoken(self):
        key =Gkey(Keys.WX_ACCESSTOKEN)
        accesstoken = myredis.get(key)
        if accesstoken is not None:
            return accesstoken.decode('utf-8')
        return ""
    def get_user_token(self,email):
        key = Gkey(Keys.USER_API_TOKEN,email)
        token = myredis.get(key)
        if token is not None:
            return token.decode('utf-8')
        return ""
    def refresh_accesstoken(self, force=0):
        key =Gkey(Keys.WX_ACCESSTOKEN)
        if force==0 or force=='0':
            accesstoken = myredis.get(key)
            if accesstoken is not None:
                ttl = myredis.ttl(key)
                if ttl > 600:
                    self.set_test_token(accesstoken.decode('utf-8'))
                    return
        self.logger.info("refresh_accesstoken")
        url=self.genUrl(f"/cgi-bin/stable_token?grant_type=client_credential&appid={config.wx_appid}&secret={config.wx_secret}")
        playload={
            "grant_type":"client_credential",
            "appid":config.wx_appid,
            "secret":config.wx_secret,
            "force_refresh":False
        }
        response = requests.post(url,json=playload,timeout=10)
        result = response.json()
        print(result)
        accesstoken = result.get('access_token')
        if accesstoken:
            expires_in = result.get('expires_in', 7200)
            myredis.setex(key, expires_in, accesstoken)
            self.set_test_token(accesstoken)
            self.logger.info(f"refresh_accesstoken success, expires_in:{expires_in}")
            return
        self.logger.error(f"refresh_accesstoken failed, result:{result}")
        
    